package com.zh.rent.controller;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import com.sun.mail.imap.protocol.IMAPProtocol;
import com.zh.rent.pojo.*;
import com.zh.rent.service.*;
import com.zh.rent.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/account")
@Api(tags="账号")
public class AccountController {

    @Autowired
    AccountService AccountServiceImpl;
    @Autowired
    InvitationService InvitationServiceImpl;
    @Autowired
    StanAccountService  StanAccountServiceImpl;
    @Autowired
    SetupService SetupServiceImpl;


    @PostMapping("/allocation")
    @ResponseBody
    @ApiOperation(value = "账号分配")
    public JsonResult allocation(String InvitationCode) {
      try {
            Invitation invitation = null;
            //查邀请码订单表
            invitation = InvitationServiceImpl.selCodeInv(InvitationCode);
            System.out.println("邀请码订单表：" + invitation.toString());
            Map<String, Object> map = new HashMap<>();
            StandbyAccount standbyAccount=null;
            Account account=null;
                 account = AccountServiceImpl.selAcc(invitation.getAccountid());
                 if(account.getStandbyid()!=null){
                     //备用账号
                     standbyAccount = StanAccountServiceImpl.selStanAcc(account.getStandbyid());
                     map.put("Account", standbyAccount);
                 }else {
                     map.put("Account", account);
                 }
            //计算到期时间
            String s = ExpireTime.plusDay(invitation.getResidue(),invitation.getUseTime().toString());
            map.put("sTime", s);
            return JsonResult.OK(map);
        }catch (Exception e){
            return JsonResult.ERROR("已经没有可用账号");
        }
    }

    public JsonResult getMailCode(String MailboxName,String Authorization){
        HttpURLConnectionUtil hcu=new HttpURLConnectionUtil();
        List<Map<String, Object>> list = new ArrayList<>();
            String url="http://127.0.0.1:5658/?type=login&username="+MailboxName+"&password="+Authorization+"&proxyip=";
        try {
            String s = hcu.sendGet(url);
            String s1 = hcu.mailText(s);
            String s2 = hcu.mailName(s1);
            Map<String, Object> map = new HashMap<>();
            map.put("Ttime","");//时间
            map.put("site", "");//发件人
            map.put("txtcontent", s2);//内容
            map.put("code", "");//邀请码
            list.add(map);
            return JsonResult.OK(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/gainCode")
    @ResponseBody
    @ApiOperation(value = "获取邮箱验证码")
    public JsonResult gainCode(String MailboxName,String Authorization,String Host) {
        //查邮箱表
        try {
            String user = MailboxName;// 邮箱的用户名
            String password = Authorization; // 邮箱的密码
            Properties prop = System.getProperties();
            prop.put("mail.store.protocol", "imap");
            prop.put("mail.imap.host", Host);
            Session session = Session.getInstance(prop);
            int total = 0;
            IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制，连接服务器
            store.connect(user, password);
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
            IMAPFolder imapFolder = (IMAPFolder) folder;

            //javamail中使用id命令有校验checkOpened, 所以要去掉id方法中的checkOpened();
            imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
                @Override
                public Object doCommand(IMAPProtocol p) throws  com.sun.mail.iap.ProtocolException {
                    p.id("FUTONG");
                    return null;
                }
            });
            imapFolder.open(Folder.READ_ONLY);
            //folder.open(Folder.READ_ONLY);//只读
           // folder.open(Folder.READ_WRITE);//读写
            // 获取总邮件数
            total = folder.getMessageCount();
            System.out.println("-----------------共有邮件：" + total
                    + " 封--------------");
            // 得到收件箱文件夹信息，获取邮件列表
            System.out.println("未读邮件数：" + folder.getUnreadMessageCount());
             Message[] messages = imapFolder.getMessages();
            int messageNumber = 0;
            ReceiveMailUtil re = null;
            List<Map<String, Object>> list = new ArrayList<>();
            System.out.println("长度"+messages.length);
            int s=messages.length>5?messages.length-5:0;
            System.out.println(s);
            if (messages.length > 0) {
                for (int i = messages.length-1; i >=s; i--) {
                    Flags flags = messages[i].getFlags();
                    re = new ReceiveMailUtil((MimeMessage) messages[i]);
                    re.getMailContent((Part) messages[i]);
                    System.out.println("发送时间：" + re.getSentDate());
                    System.out.println("地址：" + re.getFrom());
                    String bodyText = re.getBodyText();
                    String txtcontent = null;
                    txtcontent = bodyText.replaceAll("<style[^>]*?>[\\s\\S]*?<\\/style>", "");
                    txtcontent = txtcontent.replaceAll("</?[^>]+>", "");
                    txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n|</a>", "");
                    txtcontent = txtcontent.replaceAll("&nbsp;", "");
                    txtcontent = txtcontent.replaceAll("(\\w+):\\/\\/([^/:]+)(:\\d*)?([^# ]*)", "");
                    txtcontent = txtcontent.replaceAll("\\&[a-zA-Z]{1,10};", "");
                    txtcontent = txtcontent.replaceAll("[(/>)<]", "");
                    txtcontent = txtcontent.replaceAll("\\s*|\t|\r|\n|", "");
                    System.out.println("内容：" + txtcontent);
                    String e = EmailUtil.getRandomCode("验证码为", txtcontent);
                    String getyzm = EmailUtil.getyzm(e, 6);
                    Map<String, Object> map = new HashMap<>();
                    map.put("Ttime", re.getSentDate());//时间
                    map.put("site", re.getFrom());//发件人
                    map.put("txtcontent", txtcontent);//内容
                    map.put("code", getyzm);//邀请码
                    list.add(map);
                }
            }

            // 释放资源
            if (imapFolder != null)
                imapFolder.close(true);
            if (store != null)
                store.close();
            System.out.println("邮箱："+list.toString());
            return JsonResult.OK(list);
        }catch (Exception e){
            e.printStackTrace();
         return JsonResult.ERROR("错误：");

        }
    }

    @GetMapping("/logmin")
    @ResponseBody
    @ApiOperation(value = "登录时长")
    public JsonResult logmin() {
        Setup setup = SetupServiceImpl.setsetupAll();
        Integer ti=setup.getLogmin();
        return JsonResult.OK(ti);
    }
}
